package com.angis.fx.activity.sxry;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;

import com.angis.fx.activity.Enforcement;
import com.angis.fx.activity.R;
import com.angis.fx.activity.login.LoginActivity;
import com.angis.fx.data.ContextInfo;
import com.angis.fx.data.DepartmentInfo;
import com.angis.fx.data.UserInfo;
import com.angis.fx.handler.login.OnlineLoginHandler;
import com.angis.fx.util.CommonUtil;

public class SxryMActivity extends Activity {
	Activity activity;
	List<String> group;
	List<List<LinearLayout>> child;
	ExpandableListView expandList;
	FXDetailsAdapter adapter;
	TextView l_titleView;
	Button updatePeople;
	Button ok_button;
	Button s_button_people_to_main;
	private boolean isClear;
	public static String SXRP_SELECT_MEMBER = "";
	public static String SXRY_USER_DEPARTMENT = "";
	private ContextInfo contextInfo;
	private Bundle bundle;
	// private String login_result =
	// "1&AT00005&0411291651049911$浙江省文化厅#厅领导=1050324081533345:yjx=杨$sct=沈$qyw=齐$bb=鲍;厅办公室=1050712175639796:lhe=河$ni=倪$by=包;人事处=1050714145902396:;系统管理=1050610150713765:zhh=海宏$ldz=李中$xz=徐周$lw=刘伟; #0411291651049911";

	// Button s_button;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		bundle = this.getIntent().getExtras();
		contextInfo = (ContextInfo) bundle.get("contextInfo");
		isClear = bundle.getBoolean("isClear");
		setContentView(R.layout.sxry_m);
		updatePeople = (Button) findViewById(R.id.s_updatePeople);
		ok_button=(Button) findViewById(R.id.s_button_ok);
		s_button_people_to_main=(Button) findViewById(R.id.s_button_people_to_main);
		l_titleView = (TextView) findViewById(R.id.sxry_title);
		l_titleView.setText(contextInfo.getOrganizationInfo().getName());

		activity = this;
		expandList = (ExpandableListView) findViewById(R.id.expandList);
		initialData(contextInfo);
		// expandList.setGroupIndicator(this.getResources().getDrawable(
		// R.layout.expandablelistviewselector));
		adapter = new FXDetailsAdapter(this);
		expandList.setAdapter(adapter);
		expandList.setOnGroupClickListener(new OnGroupClickListener() {

			@Override
			public boolean onGroupClick(ExpandableListView arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				// Toast.makeText(activity, "[Group Click]:" + arg2,
				// Toast.LENGTH_SHORT).show();
				return false;
			}

		});

		expandList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Toast.makeText(activity, "[Group Click]:" + arg2,
						Toast.LENGTH_SHORT).show();

			}
		});

		updatePeople.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ProgressDialog lProgress = ProgressDialog.show(
						SxryMActivity.this, "", "更新中...", true);
				OnlineLoginHandler lHandler = new OnlineLoginHandler();
				TelephonyManager lTelManager = CommonUtil
						.getTelephoneManager(SxryMActivity.this);
				if (lTelManager.getDeviceId().contains("000000")) {
					// 模拟器
					contextInfo = lHandler.login(SxryMActivity.this,
							LoginActivity.g_username, LoginActivity.g_password,
							"354316036408509");
				} else {
					// 真机
					contextInfo = lHandler.login(SxryMActivity.this,
							LoginActivity.g_username, LoginActivity.g_password,
							lTelManager.getDeviceId());
				}

				if (null != contextInfo) {
					initialData(contextInfo);
					expandList.invalidateViews();
					lProgress.dismiss();
					Toast.makeText(SxryMActivity.this, "更新成功",
							Toast.LENGTH_SHORT).show();
				} else {
					lProgress.dismiss();
					Toast.makeText(SxryMActivity.this, "连接服务器出错!",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		
		
		ok_button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				addSxry();
				if(isClear){
				 Intent intent = new Intent();
				// Bundle bundle = SxryMActivity.getIntent().getExtras();
				 intent.setClass(SxryMActivity.this, Enforcement.class);
				 intent.putExtras(bundle);
				 SxryMActivity.this.startActivity(intent);
				 }
				 SxryMActivity.this.finish();
			}
		});
		
		s_button_people_to_main.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				 addSxry();
				 Intent intent = new Intent();
				// Bundle bundle = this.getIntent().getExtras();
				 intent.putExtras(bundle);
				 intent.setClass(SxryMActivity.this, SxryActivity.class);
				 SxryMActivity.this.startActivity(intent);
				 SxryMActivity.this.finish();
			}
		});
	}
	
	private void addSxry(){
		SxryMActivity.SXRP_SELECT_MEMBER = "";
		SxryMActivity.SXRY_USER_DEPARTMENT = "";
		StringBuilder lUserBuider = new StringBuilder();
		StringBuilder lDepartmentBuider = new StringBuilder();
		System.out.println(child);
		for (List<LinearLayout> list : child) {
			for (LinearLayout layout : list) {
				CheckBox view = (CheckBox) layout.getChildAt(1);
				TextView uidView = (TextView) layout.getChildAt(0);
				if (view.isChecked()) {
					System.out.println(view.getText());
					System.out.println(uidView.getText());
					SxryMActivity.SXRP_SELECT_MEMBER += view.getText()
							+ ",";
					lUserBuider.append(view.getText()).append("|");
					here:
					for (DepartmentInfo lDepart : contextInfo.getOrganizationInfo().getDpmentInfos()){
						if (lDepart.getUserInfos() != null){
							for (UserInfo lUser : lDepart.getUserInfos()){
								if (lUser.getName().equals(view.getText())){
									lDepartmentBuider.append(lDepart.getPid()).append("|");
									continue here;
								}
							}
						}
					}
				}
			}
		}
		SxryMActivity.SXRY_USER_DEPARTMENT = lUserBuider.toString() + "=" + lDepartmentBuider.toString();
	}
//
//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		MenuInflater inflater = getMenuInflater();
//		inflater.inflate(R.layout.sxrymenu, menu);
//		return true;
//
//	}
//
//	@Override
//	public boolean onOptionsItemSelected(MenuItem item) {
//		switch (item.getItemId()) {
//		case R.id.button_qd:
//			SxryMActivity.SXRP_SELECT_MEMBER = "";
//			System.out.println(child);
//			for (List<LinearLayout> list : child) {
//				for (LinearLayout layout : list) {
//					CheckBox view = (CheckBox) layout.getChildAt(1);
//					TextView uidView = (TextView) layout.getChildAt(0);
//					if (view.isChecked()) {
//						System.out.println(view.getText());
//						System.out.println(uidView.getText());
//						SxryMActivity.SXRP_SELECT_MEMBER += view.getText()
//								+ ",";
//					}
//				}
//			}
//			SxryTabs.tab_host.setCurrentTab(1);
//			// Intent intent = new Intent();
//			// Bundle bundle = this.getIntent().getExtras();
//			// intent.setClass(SxryMActivity.this, Enforcement.class);
//			// intent.putExtras(bundle);
//			// SxryMActivity.this.startActivity(intent);
//			// SxryMActivity.this.finish();
//			break;
//		case R.id.button_close:
//			break;
//		default:
//			break;
//		}
//		return super.onOptionsItemSelected(item);
//	}

	public boolean byNameSelected(UserInfo userInfo) {
		if (isClear) {
			return false;
		}
		if (SxryMActivity.SXRP_SELECT_MEMBER != null
				&& !SxryMActivity.SXRP_SELECT_MEMBER.equals("")) {
			String[] names = SxryMActivity.SXRP_SELECT_MEMBER.split(",");
			for (String name : names) {
				if (name.equals(userInfo.getName())) {
					return true;
				}
			}
		}
		return false;
	}

	public void initialData(ContextInfo contextInfo) {
		group = new ArrayList<String>();
		child = new ArrayList<List<LinearLayout>>();

		List<DepartmentInfo> infos = contextInfo.getOrganizationInfo()
				.getDpmentInfos();
		for (DepartmentInfo info : infos) {
			if (info.getUserInfos() != null)
				addInfo(info.getName(), getLinearLayout(info.getUserInfos()));
		}

	}

	public void addInfo(String p, LinearLayout[] c) {
		group.add(p);

		List<LinearLayout> item = new ArrayList<LinearLayout>();

		for (int i = 0; i < c.length; i++) {
			item.add(c[i]);
		}

		child.add(item);
	}

	LinearLayout[] getLinearLayout(List<UserInfo> userInfos) {
		List<LinearLayout> layouts = new ArrayList<LinearLayout>();
		// LinearLayout[] array=null;
		for (UserInfo userInfo : userInfos) {

			LinearLayout layout1 = new LinearLayout(this);
			TextView editText = new TextView(this);
			editText.setWidth(20);
			editText.setHeight(30);

			// editText.setText(userInfo.getUid());
			// editText.setVisibility(2);

			CheckBox box = new CheckBox(this);

			box.setChecked(byNameSelected(userInfo));
			box.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					adapter.notifyDataSetChanged();
				}
			});
			box.setHeight(30);
			box.setText(userInfo.getName());
			if(userInfo.getUid().equals(LoginActivity.g_username)){
				 box.setChecked(true);
			}
			// box.set
			// box.isChecked();
			layout1.addView(editText);
			layout1.addView(box);
			layouts.add(layout1);
		}
		return layouts.toArray(new LinearLayout[layouts.size()]);
	}

	public String getResult() {

		return null;
	}

	public class FXDetailsAdapter extends BaseExpandableListAdapter {
		Activity activity;

		public FXDetailsAdapter(Activity activity) {
			super();
			this.activity = activity;
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return child.get(groupPosition).get(childPosition);
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return childPosition;
		}

		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			return child.get(groupPosition).get(childPosition);

		}

		@Override
		public int getChildrenCount(int groupPosition) {
			// TODO Auto-generated method stub
			return child.get(groupPosition).size();
		}

		@Override
		public Object getGroup(int groupPosition) {
			// TODO Auto-generated method stub
			return group.get(groupPosition);
		}

		@Override
		public int getGroupCount() {
			// TODO Auto-generated method stub
			return group.size();
		}

		@Override
		public long getGroupId(int groupPosition) {
			// TODO Auto-generated method stub
			return groupPosition;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
					ViewGroup.LayoutParams.FILL_PARENT, 35);
			TextView text = new TextView(activity);
			text.setLayoutParams(lp);
			// Center the text vertically
			text.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
			// Set the text starting position
			text.setPadding(40, 0, 0, 0);
			text.setText(group.get(groupPosition));
			return text;
		}

		@Override
		public boolean hasStableIds() {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return true;
		}

	}
}
